package org.video.mine.activity;

import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.video.mine.GlobalStr;
import org.video.mine.MyPreference;
import org.video.mine.R;
import org.video.mine.Urls;
import org.video.mine.adapter.PlayListPlayAdapter;
import org.video.mine.databinding.ActivityPlayLoadedBinding;
import org.video.mine.databinding.ActivityPlayTestBinding;
import org.video.mine.entity.AlreadyLoadOkEntity;
import org.video.mine.entity.LoadedEntity;
import org.video.mine.entity.LookHistoryEntity;
import org.video.mine.entity.PlayListEntity;
import org.video.mine.event.RefreshHistoryEvent;
import org.video.mine.mycode.DownTask;
import org.video.mine.mycode.DownThread;
import org.video.mine.mycode.SpeedPopWindow;
import org.video.mine.network.JsoupGet;
import org.video.mine.utils.DataUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

public class PlayLoadedActivity extends AppCompatActivity implements SurfaceHolder.Callback,
        IjkMediaPlayer.OnPreparedListener,
        IjkMediaPlayer.OnCompletionListener,
        IjkMediaPlayer.OnErrorListener,
        IjkMediaPlayer.OnInfoListener, View.OnClickListener,
        IjkMediaPlayer.OnSeekCompleteListener,
        IjkMediaPlayer.OnVideoSizeChangedListener,
        SeekBar.OnSeekBarChangeListener, View.OnTouchListener{

    //https://iqiyi.cdn9-okzy.com/20200806/13598_3a5997ca/1000k/hls/index.m3u8
    private ActivityPlayLoadedBinding binding;

    private IjkMediaPlayer mPlayer;
    private boolean isShow = false;
    public static final int UPDATE_TIME = 0x0001;
    public static final int HIDE_CONTROL = 0x0002;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mHandler.sendEmptyMessage(4);
                    if (mPlayer==null)
                    return;
                    try {
                        mPlayer.reset();
                        binding.pbLoading.setVisibility(View.VISIBLE);
                        initPlayer();
                        mPlayer.setDisplay(binding.surfaceView.getHolder());
                        mPlayer.setDataSource(m3u8Url);
                        mPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "soundtouch", 1);//设置倍速是否变声1 不变，0改变
                        mPlayer.prepareAsync();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                break;
                case UPDATE_TIME:
                    updateTime();
                    mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
                    break;
                case HIDE_CONTROL:
                    hideControl();
                    break;
                case 3:
                    binding.pbLoading.setVisibility(View.GONE);
                    binding.playOrPause.setVisibility(View.INVISIBLE);
                    binding.tvError.setVisibility(View.VISIBLE);
                    break;
                case 4:
                    if (!TextUtils.isEmpty(moviename)){
                        binding.movieName.setText(moviename+set);
                        LookHistoryEntity lookHistoryEntity = new LookHistoryEntity();
                        lookHistoryEntity.setName(moviename+"("+set+")");
                        int pos = isHave(lookHistoryEntity);
                        if (pos>=0 && currentPosition==0){
                            currentPosition = historyEntities.get(pos).getPlayPosition();
                            if (currentPositionHistory>0) {
                                haveLsatHistory = false;
                            }
                            binding.tvShowMsg.setText("记忆您上次播放到"+DataUtils.timeToString(currentPositionHistory)+"，");
                        }
                    }
                    break;
                case 5:
                    saveHistory();
                    mHandler.sendEmptyMessageDelayed(5, 5000);
                    break;
                case 6:
                    haveLsatHistory = false;
                    binding.llLast.setVisibility(View.GONE);
                    break;
            }
        }
    };
    private String m3u8Url="";
    private Context context;
    private MyPreference preference;
    public boolean autoPlay = true;
    public int currentPosition=0;
    public int currentPositionHistory=0;
    public int position=0;
    private boolean playDestroyed = false;
    private boolean surfaceDestroy = false;
    private boolean prepared = false;
    private boolean isPlaying = false;
    private boolean completioned = false;
    private boolean haveLsatHistory = false;
    private String set;
    private String moviename;
    private int nowCount = 0;
    private String imageUrl = "";
    private boolean delete = false;
    private int currentVolume=0;
    private int maxVolume = 0;
    private AudioManager audioManager;
    private int minVolume = 0;
    private int width = 0;
    private int height = 0;
    private boolean surfaceCreated=false;
    private SpeedPopWindow speedPop;
    private int changeProGress=0;
    private boolean isPause = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_play_loaded);
        setContentView(binding.getRoot());

        context = this;

        IjkMediaPlayer.loadLibrariesOnce(null);
        IjkMediaPlayer.native_profileBegin("libijkplayer.so");

        initPlayer();
        initSruface();
        initView();
        initData();
    }


    private void initData() {
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        if (Build.VERSION.SDK_INT>28){
            minVolume = audioManager.getStreamMinVolume(AudioManager.STREAM_MUSIC);
        }
        currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        binding.pbVolume.setMax(maxVolume);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            binding.pbVolume.setMin(minVolume);
        }
        binding.pbVolume.setProgress(currentVolume);
        if (currentVolume<=minVolume){
            binding.ivVoice.setImageResource(R.drawable.no_voice);
        }else {
            binding.ivVoice.setImageResource(R.drawable.voice);
        }

        preference = MyPreference.getInstance();
        preference.setPreference(context);
        getNetData();
    }

    public void getNetData(){
        prepared = false;
        isPause = false;
        binding.ivSp.setText("");
        binding.rlSet.setVisibility(View.GONE);
        binding.llLast.setVisibility(View.GONE);
        binding.controlLl.setVisibility(View.GONE);
        binding.rlTopName.setVisibility(View.GONE);
        binding.pbLoading.setVisibility(View.VISIBLE);
        binding.playOrPause.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.GONE);
        set = getIntent().getStringExtra("set");
        if (set.contains(GlobalStr.saveType)) {
            set = set.substring(0, set.lastIndexOf(GlobalStr.saveType));
        }
        m3u8Url = getIntent().getStringExtra("path");
        String filePath = m3u8Url.substring(0,m3u8Url.indexOf(set)-1);
        moviename = m3u8Url.substring(m3u8Url.indexOf("movieApp/")+9,m3u8Url.indexOf(set)-1);
        historyEntity = new LookHistoryEntity();
        historyEntity.setName(moviename+"("+set+")");
        if (!TextUtils.isEmpty(m3u8Url)) {
            File file = new File(m3u8Url);
            if (file.exists()) {
                try {
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(m3u8Url);
                    String wid = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
                    String hei = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
                    width = Integer.valueOf(wid)>Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
                    height = Integer.valueOf(wid)<Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
                    mHandler.sendEmptyMessage(0);
                }catch (Exception e){
                    mHandler.sendEmptyMessage(0);
                }

            }else {
                delete = true;
            }
        }
        List<AlreadyLoadOkEntity> loadOkEntities = (List<AlreadyLoadOkEntity>) preference.getObject(MyPreference.loadok, AlreadyLoadOkEntity.class);
        if (loadOkEntities!=null && loadOkEntities.size()>0){
            for (AlreadyLoadOkEntity loadOkEntity : loadOkEntities) {
                if (loadOkEntity.getName().equals(moviename)){
                    imageUrl = loadOkEntity.getImgUrl();
                    break;
                }
            }
        }
        setPlayList(filePath);
    }

    private void getData(){
        prepared = false;
        binding.rlSet.setVisibility(View.GONE);
        binding.llLast.setVisibility(View.GONE);
        binding.controlLl.setVisibility(View.GONE);
        binding.rlTopName.setVisibility(View.GONE);
        binding.pbLoading.setVisibility(View.VISIBLE);
        binding.playOrPause.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.GONE);
        historyEntity.setName(moviename+"("+set+")");
        if (!TextUtils.isEmpty(m3u8Url)) {
            MediaMetadataRetriever retriever = new MediaMetadataRetriever();
            retriever.setDataSource(m3u8Url);
            String wid = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH);
            String hei = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT);
            width = Integer.valueOf(wid)>Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
            height = Integer.valueOf(wid)<Integer.valueOf(hei)?Integer.valueOf(wid):Integer.valueOf(hei);
            mHandler.sendEmptyMessage(0);
        }
    }


    List<LoadedEntity> fileLists = new ArrayList<>();
    private void setPlayList(String fileStr){
        File file = new File(fileStr);
        if (file.exists()){
            for (File f : file.listFiles()) {
                if (!f.isDirectory()) {
                    LoadedEntity loadedEntity = new LoadedEntity();
                    loadedEntity.setName(f.getName().substring(0,f.getName().indexOf(GlobalStr.saveType)));
                    loadedEntity.setFileDir(f.getAbsolutePath());
                    fileLists.add(loadedEntity);
                }
            }
        }else {
            Toast.makeText(context,moviename+" 文件已删除 ",Toast.LENGTH_LONG).show();
        }
        if (fileLists.size()>0){
            Collections.sort(fileLists, new Comparator<LoadedEntity>() {
                @Override
                public int compare(LoadedEntity o1, LoadedEntity o2) {
                    if (o1.getName().compareTo(o2.getName())<0){
                        return -1;
                    }else {
                        return 1;
                    }
                }
            });
            for (int i=0;i<fileLists.size();i++){
                if (fileLists.get(i).getName().contains(set)){
                    nowCount = i;
                    break;
                }
            }
            if (delete){
                Toast.makeText(context,moviename+set+" 文件已删除 "+"将为您播放 "+fileLists.get(nowCount).getName(),Toast.LENGTH_LONG).show();
                m3u8Url = fileLists.get(nowCount).getFileDir();
                set = fileLists.get(nowCount).getName();
                getData();
            }
        }else {
            Toast.makeText(context,moviename+" 文件已删除 ",Toast.LENGTH_LONG).show();
        }
    }

    private void initPlayer() {
        mPlayer = createPlayer();
        mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mPlayer.setOnCompletionListener(this);
        mPlayer.setOnErrorListener(this);
        mPlayer.setOnInfoListener(this);
        mPlayer.setOnPreparedListener(this);
        mPlayer.setOnSeekCompleteListener(this);
        mPlayer.setOnVideoSizeChangedListener(this);
    }

    public IjkMediaPlayer createPlayer() {
        IjkMediaPlayer ijkMediaPlayer = new IjkMediaPlayer();
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-handle-resolution-change", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "mediacodec-auto-rotate", 1);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "opensles", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "start-on-prepared", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "http-detect-range-support", 0);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_CODEC, "skip_loop_filter", 48);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "protocol_whitelist", "crypto,file,http,https,tcp,tls,udp");

        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT, "fflags", "fastseek");//设置seekTo能够快速seek到指定位置并播放
        //设置播放前的最大探测时间
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"analyzemaxduration",100L);
        //设置播放前的探测时间 1,达到首屏秒开效果
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"analyzeduration",1);
        //播放前的探测Size，默认是1M, 改小一点会出画面更快
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_FORMAT,"probesize",1024*10);
        //是否开启预缓冲，一般直播项目会开启，达到秒开的效果，不过带来了播放丢帧卡顿的体验
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"packet-buffering",1);
        //播放重连次数
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"reconnect",5);
        //跳帧处理,放CPU处理较慢时，进行跳帧处理，保证播放流程，画面和声音同步
//        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"framedrop",5);
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER,"max-buffer-size",500*1024);
        //某些视频在SeekTo的时候，会跳回到拖动前的位置，这是因为视频的关键帧的问题，通俗一点就是FFMPEG不兼容，视频压缩过于厉害，seek只支持关键帧，出现这个情况就是原始的视频文件中i 帧比较少
        ijkMediaPlayer.setOption(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
        return ijkMediaPlayer;
    }
    private void initView() {
        speedPop = new SpeedPopWindow(context);
        speedPop.setSpeedClick(new SpeedPopWindow.SpeedClick() {
            @Override
            public void speed(float speed) {
                if (mPlayer!=null){
                    mPlayer.setSpeed(speed);
                }
                if (speed==1.0f){
                    binding.ivSp.setText("");
                }else {
                    binding.ivSp.setText("x"+speed);
                }
                speedPop.dismissPopWindow();
            }
        });
        binding.tvSpeed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (speedPop == null) {
                    speedPop = new SpeedPopWindow(context);
                }
                speedPop.show(binding.ivSp);
                hideControl();
            }
        });

        binding.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        binding.tvError.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayer.reset();
                binding.pbLoading.setVisibility(View.VISIBLE);
                binding.playOrPause.setVisibility(View.INVISIBLE);
                binding.tvError.setVisibility(View.GONE);
                getData();
            }
        });
        binding.tvShowMsgTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPlayer!=null){
                    binding.pbLoading.setVisibility(View.VISIBLE);
                    binding.llLast.setVisibility(View.GONE);
                    mPlayer.seekTo(currentPositionHistory);
                    if (!isPlaying){
                        play();
                    }
                }
            }
        });
        binding.ivPlayPause.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play();
            }
        });
        binding.playOrPause.setOnClickListener(this);
        binding.rootRl.setOnClickListener(this);
        binding.rootRl.setOnTouchListener(this);
        binding.controlLl.setOnTouchListener(this);
        binding.tvForward.setOnClickListener(this);
        binding.tvBackward.setOnClickListener(this);
        binding.ivLast.setOnClickListener(this);
        binding.ivLastSet.setOnClickListener(this);
        binding.ivNext.setOnClickListener(this);
        binding.ivNextSet.setOnClickListener(this);
        binding.tvProgess.setOnSeekBarChangeListener(this);
        binding.surfaceView.setOnTouchListener(this);
    }

    private void initSruface(){
        binding.surfaceView.setZOrderOnTop(false);
        binding.surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        binding.surfaceView.getHolder().addCallback(this);
    }

    private void play() {
        if (!prepared)
            return;
        binding.rlSet.setVisibility(View.GONE);
        if (mPlayer == null) {
            return;
        }
        autoPlay = false;
        if (isPlaying) {
            mPlayer.pause();
            binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
            isPlaying = false;
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            mHandler.removeMessages(UPDATE_TIME);
            mHandler.removeMessages(HIDE_CONTROL);
            mHandler.removeMessages(5);
            binding.playOrPause.setVisibility(View.VISIBLE);
            isPause = true;
            binding.playOrPause.setImageResource(R.drawable.play);
        } else {
            mPlayer.start();
            binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_pause);
            completioned = false;
            isPlaying = true;
            if (haveLsatHistory){
                mHandler.sendEmptyMessageDelayed(6,6000);
            }
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
            mHandler.sendEmptyMessageDelayed(UPDATE_TIME, 500);
            mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
            mHandler.sendEmptyMessage(5);
            binding.playOrPause.setVisibility(View.INVISIBLE);
            isPause = false;
            binding.playOrPause.setImageResource(R.drawable.play_pause);
        }
    }

    long backTime = 0;
    @Override
    public void onBackPressed() {
        if (System.currentTimeMillis() - backTime < 1000) {
            saveHistory();
            PlayLoadedActivity.this.finish();
        } else {
            Toast.makeText(context, "再按一次退出播放", Toast.LENGTH_SHORT).show();
            backTime = System.currentTimeMillis();
        }
    }

    List<LookHistoryEntity> historyEntities;

    private int isHave(LookHistoryEntity historyEntity){
        int isHave = -1;
        historyEntities = (List<LookHistoryEntity>) preference.getObject(MyPreference.history,LookHistoryEntity.class);
        if (historyEntities==null){
            historyEntities = new ArrayList<>();
        }
        if (historyEntity==null)
            return -2;
        for (int i=0;i<historyEntities.size();i++){
            LookHistoryEntity item = historyEntities.get(i);
            if (item.getName().equals(historyEntity.getName())){
                isHave = i;
                break;
            }
        }
        return isHave;
    }

    @Override
    public void onCompletion(IMediaPlayer mp) {
        Log.d("suffactStatue","completion");
        completioned = true;
        binding.pbLoading.setVisibility(View.GONE);
        mHandler.removeMessages(UPDATE_TIME);
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.removeMessages(5);
        binding.controlLl.animate().setDuration(300).translationY(0);
        binding.rlTopName.animate().setDuration(300).translationY(0);
        isPlaying = false;
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        binding.playOrPause.setImageResource(R.drawable.play);
        binding.playOrPause.setVisibility(View.VISIBLE);
        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
        binding.rlSet.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onError(IMediaPlayer mp, int what, int extra) {
        Log.d("suffactStatue","error"+what);
        binding.pbLoading.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.VISIBLE);
        isPlaying = false;
        mPlayer.stop();
        mPlayer.reset();
        return false;
    }

    @Override
    public boolean onInfo(IMediaPlayer mp, int what, int extra) {
        Log.d("suffactStatue","info"+what);
        if (what==MediaPlayer.MEDIA_INFO_BUFFERING_START){
            if (binding.playOrPause.getVisibility()==View.VISIBLE) {
                isPause = true;
                binding.playOrPause.setVisibility(View.INVISIBLE);
            }
            binding.pbLoading.setVisibility(View.VISIBLE);
        }else if(what==MediaPlayer.MEDIA_INFO_BUFFERING_END){
            binding.pbLoading.setVisibility(View.GONE);
            if (isPause){
                binding.playOrPause.setVisibility(View.VISIBLE);
            }
        }
        return false;
    }

    @Override
    public void onPrepared(IMediaPlayer mp) {
        Log.d("suffactStatue","prepared,width="+width+",height="+height);
        completioned = false;
        binding.controlLl.setVisibility(View.VISIBLE);
        binding.rlTopName.setVisibility(View.VISIBLE);
        isShow = true;
        binding.pbLoading.setVisibility(View.GONE);
        binding.tvError.setVisibility(View.GONE);
        prepared = true;
        setSize();
        if (!autoPlay && currentPosition==0) {
            binding.playOrPause.setVisibility(View.VISIBLE);
        }else {
            if (currentPosition!=0) {
                binding.pbLoading.setVisibility(View.VISIBLE);
                mPlayer.seekTo(currentPosition);
            }
            binding.playOrPause.setVisibility(View.INVISIBLE);
            play();
        }
        if (haveLsatHistory){
            binding.llLast.setVisibility(View.VISIBLE);
        }
        binding.tvStartTime1.setText(DataUtils.timeToString(mp.getCurrentPosition()));
        binding.tvEndTime.setText(DataUtils.timeToString(mp.getDuration()));
        binding.tvProgess.setMax((int) mp.getDuration());
        binding.tvProgess.setProgress((int) mp.getCurrentPosition());
    }

    private void setSize() {
        Configuration newConfig = getResources().getConfiguration();
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {//横屏
            binding.playOrPause.setVisibility(View.GONE);
            getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
            System.out.println("-----------------onConfigurationChanged--------->:1");
            DisplayMetrics dm = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width1 = dm.widthPixels;
            int height1 = dm.heightPixels;

            if (width > 0 && height > 0) {
                double w = ((float) width1) / width;
                double h = ((float) height1) / height;
                if (w > h) {
                    width1 = (int) (width * h);
                } else {
                    height1 = (int) (height * w);
                }
            }

            ViewGroup.LayoutParams lp = binding.surfaceView.getLayoutParams();
            lp.width = width1;
            lp.height = height1;
            binding.surfaceView.setLayoutParams(lp);
        }
    }

    @Override
    public void onSeekComplete(IMediaPlayer mp) {
        binding.pbLoading.setVisibility(View.GONE);
        Log.d("suffactStatue","seekComplete");
    }

    @Override
    public void onVideoSizeChanged(IMediaPlayer mp, int width, int height, int sar_num, int sar_den) {
        Log.d("suffactStatue","videoSizeChange");
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d("suffactStatue","create");
        surfaceCreated = true;
        if (prepared){
            binding.pbLoading.setVisibility(View.GONE);
            playDestroyed = false;
            mPlayer.setDisplay(holder);
            surfaceDestroy = false;
            if (isPlaying){
                mPlayer.start();
            }else {
                binding.playOrPause.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d("suffactStatue","changed");
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d("suffactStatue","destroy");
        surfaceCreated = false;
        surfaceDestroy = true;
        playDestroyed = true;
        mPlayer.setDisplay(null);
        currentPosition = (int) mPlayer.getCurrentPosition();
        mPlayer.pause();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_backward:
                mHandler.removeMessages(HIDE_CONTROL);
                backWard();
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                break;
            case R.id.tv_forward:
                mHandler.removeMessages(HIDE_CONTROL);
                forWard();
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                break;
            case R.id.playOrPause:
                play();
                break;
            case R.id.root_rl:
                showControl();
                break;case R.id.iv_last_set:
            case R.id.iv_last:
                nowCount--;
                if (nowCount>=0){
                    if (isPlaying){
                        mHandler.removeMessages(5);
                        mPlayer.pause();
                        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                        isPlaying = false;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        mHandler.removeMessages(UPDATE_TIME);
                        mHandler.removeMessages(HIDE_CONTROL);
                    }
                    currentPosition = 0;
                    autoPlay = true;
                    m3u8Url = fileLists.get(nowCount).getFileDir();
                    set = fileLists.get(nowCount).getName();
                    getData();
                }else {
                    nowCount++;
                    Toast.makeText(context,"没有上一集了",Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.iv_next:
            case R.id.iv_next_set:
                nowCount++;
                if (nowCount<fileLists.size()){
                    if (isPlaying){
                        mHandler.removeMessages(5);
                        mPlayer.pause();
                        binding.ivPlayPause.setImageResource(android.R.drawable.ic_media_play);
                        isPlaying = false;
                        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                        mHandler.removeMessages(UPDATE_TIME);
                        mHandler.removeMessages(HIDE_CONTROL);
                    }
                    currentPosition = 0;
                    autoPlay = true;
                    m3u8Url = fileLists.get(nowCount).getFileDir();
                    set = fileLists.get(nowCount).getName();
                    getData();
                }else {
                    nowCount--;
                    Toast.makeText(context,"没有下一集了",Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    LookHistoryEntity historyEntity;
    private void saveHistory(){
        if (historyEntity!=null && mPlayer.getCurrentPosition()>0){
            int have = isHave(historyEntity);
            if (have==-2)
                return;
            if (have!=-1) {
                LookHistoryEntity tempLook = historyEntities.get(have);
                historyEntities.remove(have);
                historyEntity.setLoaded(true);
                historyEntity.setImgUrl(tempLook.getImgUrl());
                historyEntity.setName(moviename + "(" + set + ")");
                historyEntity.setPlayUrl(m3u8Url);
                historyEntity.setAllTimes((int) mPlayer.getDuration());

                historyEntity.setWhich(tempLook.getWhich());
                historyEntity.setPosition(position);
                historyEntity.setPlayPosition((int) mPlayer.getCurrentPosition());
                historyEntities.add(historyEntity);
                preference.setObject(MyPreference.history, historyEntities);
                EventBus.getDefault().post(new RefreshHistoryEvent());
            }else {
                historyEntity.setPlayUrl(m3u8Url);
                historyEntity.setImgUrl(imageUrl);
                historyEntity.setName(moviename + "(" + set + ")");
                historyEntity.setAllTimes((int) mPlayer.getDuration());
                historyEntity.setLoaded(true);
                historyEntity.setPlayPosition((int) mPlayer.getCurrentPosition());
                historyEntities.add(historyEntity);
                preference.setObject(MyPreference.history, historyEntities);
                EventBus.getDefault().post(new RefreshHistoryEvent());
            }
        }
    }

    /**
     * 更新播放时间
     */
    private void updateTime() {
        binding.tvStartTime1.setText(DataUtils.timeToString(
                mPlayer.getCurrentPosition()));
        binding.tvProgess.setProgress((int) mPlayer.getCurrentPosition());
    }

    /**
     * 隐藏进度条
     */
    private void hideControl() {
        isShow = false;
        getWindow().getDecorView().setSystemUiVisibility(View.INVISIBLE);//消除状态栏
        mHandler.removeMessages(UPDATE_TIME);
        binding.controlLl.animate().setDuration(300).translationY(binding.controlLl.getHeight());
        binding.rlTopName.animate().setDuration(300).translationY(-binding.rlTopName.getHeight());
    }

    /**
     * 显示进度条
     */
    private long clickTime = 0;
    private void showControl() {
        if (speedPop.isShowing()){
            speedPop.dismissPopWindow();
            return;
        }

        if (!prepared)
            return;
        if (!isShow) {
            isShow = true;
            mHandler.removeMessages(HIDE_CONTROL);
            mHandler.sendEmptyMessage(UPDATE_TIME);
            mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
            binding.controlLl.animate().setDuration(300).translationY(0);
            binding.rlTopName.animate().setDuration(300).translationY(0);
        }else {
            hideControl();
        }
        if (binding.pbLoading.getVisibility()!=View.VISIBLE && System.currentTimeMillis()-clickTime<500 && binding.pbLoading.getVisibility()!=View.VISIBLE){
            play();
        }
        clickTime = System.currentTimeMillis();
    }

    /**
     * 设置快进10秒方法
     */
    private void forWard(){
        if(mPlayer != null){
            int position = (int) mPlayer.getCurrentPosition();
            binding.pbLoading.setVisibility(View.VISIBLE);
            mPlayer.seekTo(position + 10000);
        }
    }

    /**

     * 设置快退10秒的方法

     */

    public void backWard(){
        if(mPlayer != null){
            int position;
            if (completioned){
                position = (int) mPlayer.getDuration();
            }else {
                position = (int) mPlayer.getCurrentPosition();
            }
            if(position > 10000){
                position-=10000;
            }else{
                position = 0;
            }
            binding.pbLoading.setVisibility(View.VISIBLE);
            mPlayer.seekTo(position);
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if(mPlayer != null && fromUser){
            changeProGress = progress;
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mHandler.removeMessages(HIDE_CONTROL);
    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        if (changeProGress<mPlayer.getDuration()){
            binding.rlSet.setVisibility(View.GONE);
        }
        mPlayer.seekTo(changeProGress);
        mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
    }

    private long clickDown=0;
    private float y=0;
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (v.getId()){
            case R.id.control_ll:
                Log.d("controlTouch","true");
                mHandler.removeMessages(HIDE_CONTROL);
                mHandler.sendEmptyMessageDelayed(HIDE_CONTROL, 5000);
                return true;
             case R.id.surfaceView:
                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        clickDown = System.currentTimeMillis();
                        y=event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        float changeY = event.getY()-y;
                        y = event.getY();
                        if (Math.abs(changeY)>5) {
                            currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
                            binding.llVoice.setVisibility(View.VISIBLE);
                            if (changeY < 0) {
                                currentVolume++;
                                if (currentVolume <= maxVolume) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
                                } else {
                                    currentVolume--;
                                }
                            } else {
                                currentVolume--;
                                if (currentVolume >= minVolume) {
                                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, AudioManager.FLAG_PLAY_SOUND);
                                } else {
                                    currentVolume++;
                                }
                            }
                            if (currentVolume<=minVolume){
                                binding.ivVoice.setImageResource(R.drawable.no_voice);
                            }else {
                                binding.ivVoice.setImageResource(R.drawable.voice);
                            }
                            binding.pbVolume.setProgress(currentVolume);
                        }
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis()-clickDown<500){
                            showControl();
                        }
                        binding.llVoice.setVisibility(View.GONE);
                        break;
                }
             return true;
        }
        return false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer!=null && isPlaying) {
            currentPosition = (int) mPlayer.getCurrentPosition();
            mPlayer.pause();
        }
        if (mPlayer.getCurrentPosition()!=0){
            saveHistory();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (playDestroyed) {
            binding.playOrPause.setVisibility(View.GONE);
            binding.pbLoading.setVisibility(View.VISIBLE);
        }else {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (prepared && !surfaceDestroy && surfaceCreated) {
                        isPlaying = true;
                        mPlayer.start();
                    }
                }
            },10);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (!surfaceCreated){
            initSruface();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeMessages(UPDATE_TIME);
        mHandler.removeMessages(HIDE_CONTROL);
        mHandler.removeMessages(5);
        mHandler.removeMessages(6);
        mHandler.removeMessages(0);
        mHandler.removeMessages(3);
        mHandler.removeMessages(4);
        binding.surfaceView.getHolder().removeCallback(this);
        release();
    }

    private void release() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
            mPlayer = null;
        }
        IjkMediaPlayer.native_profileEnd();
    }

}
